#!/usr/bin/env python

import sys
import re

def main():

   ids = []
   ids_finetune = []

   if len(sys.argv) >= 3:

      last_sta_sto_occ_id = 0
      last_sta_sto_occ_line = None

      dsc_match = '.*'

      if len(sys.argv) == 4:
         dsc_match = sys.argv[3]

      f = open(sys.argv[1])
      for line in f:

         if line.startswith('NAM'):

            if re.findall(sys.argv[2], line):
               id = line.split()[2]
               if not id in ids:
                  ids.append(id)
                  sys.stderr.write('keeping : \"%s\"\n' % line[:-1])

               print line,

         elif line.startswith('STA') or line.startswith('STO') or line.startswith('OCC'):
            last_sta_sto_occ_id = line.split()[2]
            if line.split()[2] in ids:
               if int(line.split()[1]) == 3:
                  last_sta_sto_occ_line = None
                  print line,
               else:
                  last_sta_sto_occ_line = line

         elif line.startswith('DSC'):

            if last_sta_sto_occ_id in ids:
               if re.search(dsc_match, line):
                  print last_sta_sto_occ_line,
                  print line,

         else:
            if last_sta_sto_occ_line:
               print last_sta_sto_occ_line,
            print line,

      f.close()

   else:
      sys.stderr.write("Usage: %s tdifile NAM-pattern [DSC-pattern]\n" % sys.argv[0])

if __name__ == "__main__":
   main()
